package com.jhxy.algorithm.twosum;

import java.util.HashMap;
import java.util.Map;

/**
 * 使用hash表实现两数之和算法
 */
public class HashTableTwoSum {


    public int[] hashTable(int[] nums, int target) {
        int[] res = new int[2];

        //1.将数组转成hash表，key为nums数组中的值，value为nums数组的index角标
        Map<Integer, Integer> hashMap = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            hashMap.put(nums[i], i);
        }

        //2.算法的主题
        for (int i = 0; i < nums.length; i++) {
            if (hashMap.containsKey(target - nums[i])) {
                int j = hashMap.get(target - nums[i]);
                //防止出现nums = [3],当时target = 6的情况
                if (i != j) {
                    return new int[]{i, j};
                }
            }
        }

        return res;
    }


    public static void main(String[] args) throws InterruptedException {
        InputForTwoNumberSum ins = new InputForTwoNumberSum("0,4,2,1,2,3,2,3,4,4,4", "8");

        HashTableTwoSum hashTableTwoSum = new HashTableTwoSum();

        for (int i : hashTableTwoSum.hashTable(ins.nums, ins.target)) {
            System.out.println(i);
        }
    }
}
